package com.thiswhyme.easyexcel.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.thiswhyme.common.expection.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 默认数据获取Listener
 * @author: thiswhyme
 * @date: 2021/9/15
 */
@Slf4j
public class DefaultDataGetListener<T> extends AnalysisEventListener<T> {

    /**
     * 数据处理上限
     */
    public static final int MAX_COUNT = 10000;

    /**
     * 数据超出上限处理策略
     */
    private OutOfLimitPolicy policy;

    private List<T> list = new ArrayList<>();

    public DefaultDataGetListener() {
        this.policy = OutOfLimitPolicy.DISCARD;
    }

    public DefaultDataGetListener(OutOfLimitPolicy policy) {
        this.policy = policy;
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        if (list.size() < MAX_COUNT + 1) {
            list.add(data);
        } else {
            switch (policy) {
                case DISCARD:
                    log.info("数据超出限制:{}, 丢弃多余数据", MAX_COUNT);
                    break;
                case EXCEPTION_THROW:
                    throw new BusinessException("数据超出限制");
                default:
                    break;
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成，共{}条", list.size());
    }

    /**
     * 返回excel读取的数据
     * @return excel读取的数据
     */
    public List<T> getData() {
        return list;
    }
}
